package cn.com.gzheroli.bfw.web.system.controler.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.gzheroli.bfw.pojo.base.TSFunction;
import cn.com.gzheroli.bfw.pojo.base.TSIcon;
import cn.com.gzheroli.bfw.pojo.base.TSOperation;
import cn.com.gzheroli.bfw.pojo.base.TSRoleFunction;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.core.common.controller.BaseController;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.model.json.TreeGrid;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.LogUtil;
import cn.com.gzheroli.core.util.MyBeanUtils;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.rabbitmq.service.log.LogService;
import cn.com.gzheroli.service.bfw.FunctionService;
import cn.com.gzheroli.service.bfw.IconService;
import cn.com.gzheroli.service.bfw.UserService;
import cn.com.gzheroli.tag.core.DataGrid;
import cn.com.gzheroli.tag.vo.easyui.ComboTreeModel;
import cn.com.gzheroli.util.TagUtil;

/**
 * 菜单权限处理类
 * 
 * 
 */
@Controller
@RequestMapping("/functionController")
public class FunctionController  {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(FunctionController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private SystemService systemService;
	private String message = null;
	@Autowired
	private FunctionService functionService;
	
	@Autowired
	private LogService logService;
	@Autowired
	private IconService iconService;
	@Autowired
	private CommonService commonService;


	/**
	 * 权限列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "function")
	public ModelAndView function() {
		return new ModelAndView("system/function/functionList");
	}

	/**
	 * 操作列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "operation")
	public ModelAndView operation(HttpServletRequest request, String functionId) {
		// ----------------------------------------------------------------
		// ----------------------------------------------------------------
		request.setAttribute("functionId", functionId);
		// ----------------------------------------------------------------
		// ----------------------------------------------------------------
		return new ModelAndView("system/operation/operationList");
	}

	/**
	 * easyuiAJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		/*CriteriaQuery cq = new CriteriaQuery(TSFunction.class, dataGrid);
		this.systemService.getDataGridReturn(cq, true);*/
		Map para=new HashMap();
		Integer page = Integer.valueOf(Integer.parseInt(request.getParameter("page")));
	    Integer rows = Integer.valueOf(Integer.parseInt(request.getParameter("rows")));
	    Integer start = Integer.valueOf((page.intValue() - 1) * rows.intValue())+1;
	    Integer end = Integer.valueOf(page.intValue() * rows.intValue() );
	    para.put("maxResults", end.intValue());
	    para.put("firstResult", start.intValue());
	    para.put("pageSize", rows);
	    para.put("beginRow", (page-1)*rows);//mysql
		List functionList=functionService.getFunctionMenuList(para);
		Long Acount=functionService.getFunctionMenuCount(para);
		dataGrid.setResults(functionList);
		dataGrid.setTotal(Acount.intValue());
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * easyuiAJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "opdategrid")
	public void opdategrid(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		String functionId = oConvertUtils.getString(request
				.getParameter("functionId"));
		Map para=new HashMap();
		para.put("functionId", functionId);
		Integer page = Integer.valueOf(Integer.parseInt(request.getParameter("page")));
	    Integer rows = Integer.valueOf(Integer.parseInt(request.getParameter("rows")));
	    Integer start = Integer.valueOf((page.intValue() - 1) * rows.intValue())+1;
	    Integer end = Integer.valueOf(page.intValue() * rows.intValue() );
	    para.put("maxResults", end.intValue());
	    para.put("firstResult", start.intValue());
	    para.put("pageSize", rows);
	    para.put("beginRow", (page-1)*rows);//mysql
		List functionList=functionService.getMenuOptList(para);
		Long Acount=functionService.getMenuOptCount(para);
		dataGrid.setResults(functionList);
		dataGrid.setTotal(Acount.intValue());
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除权限
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TSFunction function, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		function = commonService.getEntity(TSFunction.class, function.getId());
		if(function!=null){
			message = "权限: " + function.getFunctionName() + "被删除成功";
			Map paras=new HashMap();
			paras.put("functionId", function.getId());
			/*SQL sql=new SQL();
			
			sql.WHERE("FUNCTION_ID=#{functionId}");*/
			String sql="delete from T_S_ROLE_FUNCTION where FUNCTION_ID=#{functionId}";
			commonService.deleteBySql(sql, paras);
					/*.updateBySqlString("delete from T_S_ROLE_FUNCTION where functionid='"
							+ function.getId() + "'");*/

			commonService.delete(TSFunction.class,function.getId());
			logService.addLogRoleauth(message, Globals.Log_Type_DEL, null,LogUtil.logReqMap(request));
		}
		

		// // 删除权限时先删除权限与角色之间关联表信息
		// List<TSRoleFunction> roleFunctions =
		// systemService.findByProperty(TSRoleFunction.class, "TSFunction.id",
		// function.getId());
		//
		// if (roleFunctions.size() > 0) {
		// j.setMsg("菜单已分配无法删除");
		//
		// }
		// else {
		// userService.delete(function);
		// systemService.addLog(message, Globals.Log_Type_DEL,
		// Globals.Log_Leavel_INFO);
		// }

		return j;
	}

	/**
	 * 删除操作
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "delop")
	@ResponseBody
	public AjaxJson delop(TSOperation operation, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		operation = commonService.getEntity(TSOperation.class,
				operation.getId());
		message = "操作: " + operation.getOperationName() + "被删除成功";
		commonService.delete(TSOperation.class,operation.getId());
		logService.addLogRoleauth(message, Globals.Log_Type_DEL, null,LogUtil.logReqMap(request));

		return j;
	}

	/**
	 * 权限录入
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "saveFunction")
	@ResponseBody
	public AjaxJson saveFunction(TSFunction function, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		// ----------------------------------------------------------------
		// ----------------------------------------------------------------
		String functionOrder = function.getFunctionOrder();
		if (StringUtils.isEmpty(functionOrder)) {
			function.setFunctionOrder("0");
		}
		// ----------------------------------------------------------------
		// ----------------------------------------------------------------
		if (function.getParentId()==null||function.getParentId().equals("")) {
			function.setParentId("");
		} else {
			/*TSFunction parent = commonService.getEntity(TSFunction.class,
					function.getParentId());
			function.setFunctionLevel(Short.valueOf(parent.getFunctionLevel()
					+ 1 + ""));*/
		}
		String functionLevel=request.getParameter("functionLevel")==null?"0":request.getParameter("functionLevel");
		function.setFunctionLevel(Short.valueOf(functionLevel));
		if(functionLevel.equals("0")){
			function.setParentId("");
		}
			
		if (StringUtil.isNotEmpty(function.getId())) {
			message = "权限: " + function.getFunctionName() + "被更新成功";
			//systemService.saveOrUpdate(function);
			/*Map parameter=new HashMap();
			MyBeanUtils.copyBean2Map(parameter, function);*/
			
			functionService.updateFunction(function);
			logService.addLogRoleauth(message, Globals.Log_Type_UPDATE,null, LogUtil.logReqMap(request));
			// ----------------------------------------------------------------
			// ----------------------------------------------------------------


			// ----------------------------------------------------------------
			// ----------------------------------------------------------------

		} else {
			if (function.getFunctionLevel().equals(Globals.Function_Leave_ONE)) {
				List<TSFunction> functionList = commonService.findByProperty(
						TSFunction.class, "functionLevel",
						Globals.Function_Leave_ONE);
				// int ordre=functionList.size()+1;
				// function.setFunctionOrder(Globals.Function_Order_ONE+ordre);
				function.setFunctionOrder(function.getFunctionOrder());
			} else {
				List<TSFunction> functionList = commonService.findByProperty(
						TSFunction.class, "functionLevel",
						Globals.Function_Leave_TWO);
				// int ordre=functionList.size()+1;
				// function.setFunctionOrder(Globals.Function_Order_TWO+ordre);
				function.setFunctionOrder(function.getFunctionOrder());
			}
			message = "权限: " + function.getFunctionName() + "被添加成功";
			//systemService.save(function);
			function.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
			functionService.saveFunction(function);
			logService.addLogRoleauth(message, Globals.Log_Type_INSERT,null, LogUtil.logReqMap(request));

		}

		return j;
	}

	/**
	 * 操作录入
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "saveop")
	@ResponseBody
	public AjaxJson saveop(TSOperation operation, HttpServletRequest request) {
		String pid = request.getParameter("functionId");
		if (pid.equals("")) {
			operation.setFunctionId(pid);
		}
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(operation.getId())) {
			message = "操作: " + operation.getOperationName() + "被更新成功";
			commonService.update(operation);
			logService.addLogRoleauth(message, Globals.Log_Type_UPDATE,null, LogUtil.logReqMap(request));
		} else {
			message = "操作: " + operation.getOperationName() + "被添加成功";
			operation.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
			commonService.save(operation);
			logService.addLogRoleauth(message, Globals.Log_Type_INSERT, null,LogUtil.logReqMap(request));

		}

		return j;
	}

	/**
	 * 权限列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(TSFunction function, HttpServletRequest req) {
		String functionid = req.getParameter("id");
		//List<TSFunction> fuinctionlist = systemService.getList(TSFunction.class);
		List<Map> fuinctionlist = new ArrayList<Map>();
		Map dataMap=new HashMap();
		fuinctionlist =functionService.getFunctionList(dataMap);
		req.setAttribute("flist", fuinctionlist);
		Map datamap=new HashMap();
		datamap.put("status", "1");
		//List<TSIcon> iconlist=iconService.getAllIcon(datamap);
		//req.setAttribute("iconlist", iconlist);
		if (functionid != null) {
			function = commonService.getEntity(TSFunction.class, functionid);
			req.setAttribute("function", function);
		}
		if (function.getParentId() != null) {
			function.setFunctionLevel((short) 1);
			/*function.setTSFunction((TSFunction) systemService.getEntity(
					TSFunction.class, function.getParentId()));*/
			TSFunction pfunc=(TSFunction) commonService.getEntity(
					TSFunction.class, function.getParentId());
			function.setParentId(pfunc.getId());
			req.setAttribute("function", function);
		}
		return new ModelAndView("system/function/function");
	}
	/**
	 * 获取菜单信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "getFunctionData")
	@ResponseBody
	public AjaxJson getFunctionData(TSFunction function, HttpServletRequest request) {
		AjaxJson j=new AjaxJson();
		String functionid = request.getParameter("id");
		//List<TSFunction> fuinctionlist = systemService.getList(TSFunction.class);
		List<Map> fuinctionlist = new ArrayList<Map>();
		//Map dataMap=new HashMap();
		//fuinctionlist =functionService.getFunctionList(dataMap);
		//req.setAttribute("flist", fuinctionlist);
		Map datamap=new HashMap();
		datamap.put("status", "1");
		//List<TSIcon> iconlist=iconService.getAllIcon(datamap);
		//req.setAttribute("iconlist", iconlist);
		if (functionid != null) {
			//function = commonService.getEntity(TSFunction.class, functionid);
			function =functionService.getFuncData(functionid);
		}
		if (function.getParentId() != null) {
			function.setFunctionLevel((short) 1);
			TSFunction pfunc=(TSFunction) commonService.getEntity(
					TSFunction.class, function.getParentId());
			function.setParentId(pfunc.getId());
		}
		j.setObj(function);
		j.setSuccess(true);
		j.setMsg("获取成功");
		return j;
	}

	/**
	 * 操作列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdateop")
	public ModelAndView addorupdateop(TSOperation operation,
			HttpServletRequest req) {
		Map datamap=new HashMap();
		datamap.put("status", "1");
		//List<TSIcon> iconlist=iconService.getIconList(datamap);
		//req.setAttribute("iconlist", iconlist);
		if (operation.getId() != null) {
			operation = commonService.getEntity(TSOperation.class,
					operation.getId());
			req.setAttribute("operation", operation);
		}
		String functionId = oConvertUtils.getString(req
				.getParameter("functionId"));
		req.setAttribute("functionId", functionId);
		return new ModelAndView("system/operation/operation");
	}
	/**
	 * 获取菜单操作信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "getOperationData")
	@ResponseBody
	public AjaxJson getOperationData(TSOperation operation,HttpServletRequest request) {
		AjaxJson j=new AjaxJson();
		Map datamap=new HashMap();
		datamap.put("status", "1");
		//List<TSIcon> iconlist=iconService.getIconList(datamap);
		//req.setAttribute("iconlist", iconlist);
		if (operation.getId() != null) {
			operation = commonService.getEntity(TSOperation.class,
					operation.getId());
		}
		j.setObj(operation);
		j.setSuccess(true);
		j.setMsg("获取成功");
		return j;
	}

	/**
	 * 权限列表
	 */
	@RequestMapping(params = "functionGrid")
	@ResponseBody
	public List<Map> functionGrid(HttpServletRequest request,
			TreeGrid treegrid) {
		List<Map> treeGrids = new ArrayList<Map>();
		Map dataMap=new HashMap();
		dataMap.put("pid", request.getParameter("id"));
		treeGrids =functionService.getFunctionList(dataMap);
		return treeGrids;
	}

	/**
	 * 权限列表
	 */
	@RequestMapping(params = "functionList")
	@ResponseBody
	public void functionList(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		String id = oConvertUtils.getString(request.getParameter("id"));
		List<Map> treeGrids = new ArrayList<Map>();
		Map dataMap=new HashMap();
		if (id != null) 
		dataMap.put("pid", id);
		treeGrids =functionService.getFunctionList(dataMap);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 父级权限下拉菜单
	 */
	@RequestMapping(params = "setPFunction")
	@ResponseBody
	public List<Map> setPFunction(HttpServletRequest request,
			ComboTree comboTree) {
		Map para=new HashMap();
		if(null != request.getParameter("selfId")){
			para.put("selfId", request.getParameter("selfId"));
		}
		para.put("pid", comboTree.getId());
		List<Map> functionList=functionService.getFunctionMenuList(para);
		List<Map> result=new ArrayList();
		for(Map menu:functionList){
			Map menuMap=new HashMap();
			menuMap.put("id", menu.get("id"));
			menuMap.put("text", menu.get("functionName"));
			menuMap.put("state", menu.get("state"));
			menuMap.put("parentId", menu.get("parentId"));
			result.add(menuMap);
		}
		return result;
		/*List<ComboTree> comboTrees = new ArrayList<ComboTree>();
		ComboTreeModel comboTreeModel = new ComboTreeModel("ID",
				"FUNCTIONNAME", "TSFunctions");
		comboTrees = systemService.ComboTree(functionList, comboTreeModel, null,true);
		return comboTrees;*/
	}
	
}
